package com.iticit.util;


import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

@Slf4j
public class HttpClientUtils {

    //设置链接超时和请求超时等参数，否则会长期停止或者崩溃
    private static RequestConfig REQUEST_CONFIG = RequestConfig.custom()
            .setSocketTimeout(60000)
            .setConnectTimeout(60000)
            .setConnectionRequestTimeout(60000)
            .build();

    public static HttpResult sendHttpPostWithCustomHeader(String url, String data, Map<String, String> headerMap)
            throws Exception {
        CloseableHttpClient client = null;
        HttpResult result = new HttpResult();
        try {
            client = HttpClients.custom()
                    .setDefaultRequestConfig(REQUEST_CONFIG).build();
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(data, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);
            if (headerMap != null && headerMap.size() > 0) {
                headerMap.forEach((k, v) -> httpPost.setHeader(k, v));
            }
            CloseableHttpResponse response = client.execute(httpPost);
            log.info("response ---> {}", response);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new RuntimeException(response.getStatusLine().toString());
            }
            Header[] headers = response.getAllHeaders();
            if (headers != null && headers.length > 0) {
                Map<String, String> temHeaderMap = new HashMap<String, String>();
                Arrays.stream(headers).forEach(e -> temHeaderMap.put(e.getName(), e.getValue()));
                result.setHeaderMap(temHeaderMap);
            }
            HttpEntity entityResult = response.getEntity();
            result.setResult(EntityUtils.toString(entityResult));
            return result;
        } catch (Exception e) {
            throw e;
        } finally {
            IOUtils.closeQuietly(client);
        }
    }
}
